import axios from 'axios'

//请求拦截器
axios.interceptors.request.use((config)=>{
    let accessToken=localStorage.getItem('accessToken')
    if(accessToken){
        config.headers.Authorization='Bearer '+accessToken
    }
    return config
})

//无感刷新
let refreshToken=async()=>{
    let {data:{code,data}} = await axios.get('http://127.0.0.1:3000/long/refresh',{
        params:{
            token:localStorage.getItem('refreshToken')
        }
    })
    if(code==200){
        localStorage.setItem('accessToken', data.accessToken)
        localStorage.setItem('refreshToken', data.refreshToken)
    }
    return code
}

let refreshing=false
let queue=[]
//响应拦截器
 //合并请求
axios.interceptors.response.use((response)=>{
    return response
},
async(error)=>{
    let {status,data,config}=error.response
    if(status ==401 && !config.url.includes('/refresh')){
        
        let code =await refreshToken()
        
        if(code==200){
            console.log(code);
            return axios(config)
        }else{
            alert(data.msg || '登录过期')
            console.log(code);
            return []
        }
    }else{
        return error.response
    }
}
)

export default axios